#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/7/12 1:51
# @Author : LZQ
# @Version：V 0.1
# @File : users.py
# @desc :
from . import api, user
from __init__ import db, redis_store
from app.utils.status_code import RET
from flask import current_app, g, session, request, jsonify
import math
from sqlalchemy.exc import IntegrityError
from sqlalchemy import or_, and_, desc
from app.models import User, Manager,Role
import json, time
from app.token_verify import verify
from app.utils.token import certify_token, generate_token


@api.route("/users", methods=['GET'])
@verify
def get_users():
    data = request.args
    query = '%{}%'.format(data.get("query"))
    pagenum = int(data.get("pagenum"))
    pagesize = int(data.get("pagesize"))
    filters = [
        Manager.mg_name.like(query)
    ]
    result = {}
    try:
        managers = Manager.query.filter(*filters).paginate(pagenum, pagesize)
        print(managers.items)
        manager_list = []
        for manager in managers.items:
            manager_list.append(manager.to_dict())
        print(manager_list)
        result = {'meta': {"code": 200, 'msg': '获取管理员列表成功'},
                  "data": {"users": manager_list, "totalPage": managers.total}}
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DATABASE_ERROR)
    return jsonify(result)


@user.route("/<string:uid>/state/<string:state>", methods=['PUT'])
@verify
def alert_user(uid, state):
    if not all([uid, state]):
        return jsonify({"code": 400, "msg": "参数不完整"})
    else:
        try:
            if state in ['true', 'True']:
                state = True
            else:
                state = False
                Manager.query.filter(Manager.mg_id == uid).update({"mg_state": 0 if state else 1})
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(RET.USER_ALERT_STATE_FAIL)
    return jsonify(RET.USER_ALERT_STATE_SUCCESS)


@api.route('/editUser', methods=['POST'])
@verify
def editUser():
    '''
    修改用户数据
    接受数据为表单数据
    :return:
    '''
    data = json.loads(request.get_data())
    mg_name = data.get("mg_name")
    mg_mobile = data.get("mg_mobile")
    mg_email = data.get("mg_email")
    mg_id = data.get("mg_id")
    if not all([mg_name, mg_mobile, mg_email, mg_id]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        manage = Manager.query.filter(Manager.mg_id == mg_id).first()
        manage.mg_name = mg_name
        manage.mg_mobile = mg_mobile
        manage.mg_email = mg_email
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
    print(mg_name, mg_mobile, mg_email, mg_id)
    return jsonify(RET.USER_EDIT_SUCCESS)


@user.route('/delete', methods=['POST'])
@verify
def delete():
    data = json.loads(request.get_data())
    mg_id = data.get('mg_id')
    if mg_id:
        try:
            count = Manager.query.filter(Manager.mg_id == mg_id).delete()
            if count == 0:
                return jsonify(RET.USER_NOT_EXIST)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(RET.USER_DELETE_FAIL)
        return jsonify(RET.USER_DELETE_SUCCESS)
    else:
        return jsonify(RET.PARAMS_NOTALL)



@user.route("/setRole", methods=["POST"])
@verify
def setRole():
    datas = []
    data = json.loads(request.get_data())
    mg_id = data.get("mg_id")
    role_id = data.get('role_id')
    if not role_id:
        role_id='0'
    if not all([mg_id]):
        return jsonify(RET.PARAMS_NOTALL)
    try:
        manager = Manager.query.filter(Manager.mg_id == mg_id).first()
        manager.role_id = role_id
        db.session.merge(manager)
        db.session.commit()
        datas.append(manager.to_dict())
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify({"data":datas,"meta":RET.USER_UPDATE_ROLE_FAIL})
    return jsonify({"data":datas,"meta":RET.USER_UPDATE_ROLE_SUCCESS})




@api.route("/is_login", methods=['GET'])
@verify
def islogin():
    return jsonify(RET.OK)
